package cn.tuzirpa;

import cn.tuzirpa.config.DatabaseConfig;
import cn.tuzirpa.executor.SqlFileExecutor;
import cn.tuzirpa.manager.DatabaseManager;
import cn.tuzirpa.tracker.SqlExecutionTracker;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Scanner;

/**
 * 数据库初始化工具包主类
 * 提供命令行界面来配置数据库并执行SQL文件
 */
public class App {
    
    private static final Logger logger = LoggerFactory.getLogger(App.class);
    
    public static void main(String[] args) {
        logger.info("=== 数据库初始化工具包 ===");
        
        try {
            // 创建配置
            DatabaseConfig config = createDatabaseConfig();
            
            // 创建数据库管理器
            DatabaseManager databaseManager = new DatabaseManager(config);
            
            // 测试连接
            if (!testDatabaseConnection(databaseManager)) {
                logger.error("数据库连接失败，程序退出");
                return;
            }
            
            // 创建数据库（如果不存在）
            createDatabaseIfNotExists(databaseManager);
            
            // 创建执行跟踪器
            SqlExecutionTracker executionTracker = new SqlExecutionTracker(databaseManager);
            
            // 创建SQL执行器
            SqlFileExecutor sqlExecutor = new SqlFileExecutor(databaseManager, executionTracker);
            
            // 主菜单循环
            showMainMenu(sqlExecutor, executionTracker);
            
            // 关闭资源
            databaseManager.close();
            
        } catch (Exception e) {
            logger.error("程序执行失败", e);
        }
    }
    
    /**
     * 创建数据库配置
     */
    private static DatabaseConfig createDatabaseConfig() {
        Scanner scanner = new Scanner(System.in);
        
        System.out.println("\n=== 数据库配置 ===");
        
        System.out.print("请输入数据库URL (例如: jdbc:mysql://localhost:3306): ");
        String url = scanner.nextLine().trim();
        
        System.out.print("请输入用户名: ");
        String username = scanner.nextLine().trim();
        
        System.out.print("请输入密码: ");
        String password = scanner.nextLine().trim();
        
        System.out.print("请输入数据库名: ");
        String databaseName = scanner.nextLine().trim();
        
        System.out.print("请输入字符编码 (默认: utf8mb4): ");
        String charset = scanner.nextLine().trim();
        if (charset.isEmpty()) {
            charset = "utf8mb4";
        }
        
        DatabaseConfig config = new DatabaseConfig(url, username, password, databaseName, charset);
        logger.info("数据库配置完成: {}", config);
        
        scanner.close();
        return config;
    }
    
    /**
     * 测试数据库连接
     */
    private static boolean testDatabaseConnection(DatabaseManager databaseManager) {
        logger.info("测试数据库连接...");
        
        if (databaseManager.testBaseConnection()) {
            logger.info("基础数据库连接测试成功");
        } else {
            logger.error("基础数据库连接测试失败");
            return false;
        }
        
        return true;
    }
    
    /**
     * 创建数据库（如果不存在）
     */
    private static void createDatabaseIfNotExists(DatabaseManager databaseManager) {
        logger.info("检查数据库是否存在...");
        
        if (!databaseManager.databaseExists()) {
            logger.info("数据库不存在，开始创建...");
            databaseManager.createDatabase();
        } else {
            logger.info("数据库已存在，跳过创建");
        }
    }
    
    /**
     * 显示主菜单
     */
    private static void showMainMenu(SqlFileExecutor sqlExecutor, SqlExecutionTracker executionTracker) {
        Scanner scanner = new Scanner(System.in);
        
        try {
            while (true) {
                System.out.println("\n=== 主菜单 ===");
                System.out.println("1. 执行SQL文件目录");
                System.out.println("2. 查看执行历史");
                System.out.println("3. 清理执行记录");
                System.out.println("4. 退出程序");
                System.out.print("请选择操作 (1-4): ");
                
                String choice;
                try {
                    choice = scanner.nextLine().trim();
                } catch (java.util.NoSuchElementException e) {
                    System.out.println("\n检测到输入流关闭，程序自动退出");
                    return;
                }
                
                if (choice.isEmpty()) {
                    System.out.println("请输入有效选择");
                    continue;
                }
                
                switch (choice) {
                    case "1":
                        executeSqlFiles(sqlExecutor, scanner);
                        break;
                    case "2":
                        executionTracker.printExecutionHistory();
                        break;
                    case "3":
                        clearExecutionHistory(executionTracker, scanner);
                        break;
                    case "4":
                        System.out.println("程序退出");
                        return;
                    default:
                        System.out.println("无效选择，请重新输入");
                }
            }
        } finally {
            scanner.close();
        }
    }
    
    /**
     * 执行SQL文件
     */
    private static void executeSqlFiles(SqlFileExecutor sqlExecutor, Scanner scanner) {
        System.out.print("请输入SQL文件目录路径: ");
        String directoryPath;
        try {
            directoryPath = scanner.nextLine().trim();
        } catch (java.util.NoSuchElementException e) {
            System.out.println("输入流关闭，返回主菜单");
            return;
        }
        
        if (directoryPath.isEmpty()) {
            System.out.println("目录路径不能为空");
            return;
        }
        
        try {
            logger.info("开始执行SQL文件目录: {}", directoryPath);
            sqlExecutor.executeSqlFiles(directoryPath);
            System.out.println("SQL文件执行完成");
        } catch (Exception e) {
            logger.error("执行SQL文件失败", e);
            System.out.println("执行SQL文件失败: " + e.getMessage());
        }
    }
    
    /**
     * 清理执行记录
     */
    private static void clearExecutionHistory(SqlExecutionTracker executionTracker, Scanner scanner) {
        System.out.print("确定要清理所有执行记录吗？(y/N): ");
        String confirm;
        try {
            confirm = scanner.nextLine().trim().toLowerCase();
        } catch (java.util.NoSuchElementException e) {
            System.out.println("输入流关闭，返回主菜单");
            return;
        }
        
        if ("y".equals(confirm) || "yes".equals(confirm)) {
            try {
                executionTracker.clearExecutionHistory();
                System.out.println("执行记录已清理");
            } catch (Exception e) {
                logger.error("清理执行记录失败", e);
                System.out.println("清理执行记录失败: " + e.getMessage());
            }
        } else {
            System.out.println("操作已取消");
        }
    }
}
